use std::borrow::ToOwned;
use std::sync::{Arc, Mutex};
use std::thread::spawn;

use eframe::{CreationContext, egui};
use tokio::runtime::Runtime;

use crate::web::start_web;

pub struct MainApp {
    pub port: String,
    pub is_web_start: Arc<Mutex<bool>>,
}

impl Default for MainApp {
    fn default() -> Self {
        MainApp {
            port: "8080".to_owned(),
            is_web_start: Arc::new(Mutex::new(false)),
        }
    }
}

impl MainApp {
    pub fn new(ctx: &CreationContext<'_>) -> Self {
        load_fonts(&ctx.egui_ctx);
        Self::default()
    }
}

impl eframe::App for MainApp {
    fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.vertical_centered(|ui| {
                ui.heading("嘿嘿嘿");
            });
            ui.separator();
            ui.horizontal_top(|ui| {
                ui.label("端口号");
                ui.text_edit_singleline(&mut self.port);

                if let Ok(mut r) = self.is_web_start.lock() {
                    if *r {
                        if ui.button("关闭").clicked() {
                            println!("关闭");
                            *r = false;
                        }
                    } else {
                        if ui.button("开启").clicked() {
                            println!("开启");
                            let is_web_start_clone = Arc::clone(&self.is_web_start);

                            let rt = Runtime::new().expect("Unable to create Runtime");

                            spawn(move || {
                                rt.block_on(async {
                                    let mut is_web_start = is_web_start_clone.lock().unwrap();
                                    *is_web_start = true;
                                    drop(is_web_start);
                                    start_web().await.unwrap();
                                })
                            });
                        }
                    }
                }
            });
        });
    }
}


pub fn load_fonts(ctx: &egui::Context) {
    let mut fonts = egui::FontDefinitions::default();
    fonts.font_data.insert(
        "my_font".to_owned(),
        egui::FontData::from_static(include_bytes!("../../../fonts/simsun.ttc")),
    );
    fonts
        .families
        .entry(egui::FontFamily::Proportional)
        .or_default()
        .insert(0, "my_font".to_owned());

    fonts
        .families
        .entry(egui::FontFamily::Monospace)
        .or_default()
        .push("my_font".to_owned());
    ctx.set_fonts(fonts);
}